<template>
  <div class="map-search-container">
    <span>搜索地点</span>
    <el-select v-model="valueSearch" filterable remote reserve-keyword placeholder="请输入关键词"
      :remote-method="remoteMethod" :loading="loading">
      <el-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
  <tlbs-map ref="mapRef" :api-key="txKey" :center="center" :zoom="zoom" :control="control" @click="onClick"
    @map_inited="onMapInited">
    <!-- @click="eventClick" -->
    <tlbs-multi-marker ref="markerRef" :geometries="geometries" :styles="styles" :options="options" />
  </tlbs-map>
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from 'vue'
import { suggestionInfo } from '@/api/device/mapInfo.js'

const txKey = 'LTOBZ-VNRKJ-L5KFS-DHZGP-AGGGK-3MFPN'
const props = defineProps({
  // 复杂对象
  Location: {
    type: Object,
    default: () => ({})
  }
})

console.log('props=', props.Location)

const emit = defineEmits(['locationSelected'])

const mapRef = ref(null)
const markerRef = ref(null)
const center = ref(props.Location)
const zoom = ref(14)

const onClick = (e) => {
  console.log(e)
  console.log(e.latLng)
  //更新标记数据
  markerRef.value.marker.setGeometries([
    {
      styleId: 'marker',
      position: e.latLng,
      properties: {
        title: '这是自定义数据'
      }
    }
  ])
  // center.value = e.latLng
  getLayerInstance()
  console.log('e.latLng=', e.latLng)
  emit('locationSelected', e.latLng)
}
//监听回调函数（非匿名函数）
const eventClick = (evt) => {
  // markerID.innerHTML = 'markerID:' + evt.geometry.id
  // position.innerHTML = '当前marker位置：' + evt.geometry.position.toString()
  console.log('markerID:' + evt.geometry.id)
  console.log('markerID:' + evt.geometry.position.toString())
  console.log(evt.geometry.properties)
}

//position 类型初始化
let local_position = {}

// 响应式数据声明
const valueSearch = ref({})
// 方法 1：使用 watch
watch(valueSearch, (newVal) => {
  console.log('输入内容变化:', newVal)
  // 执行搜索逻辑
  // performSearch(newVal)
  console.log(newVal.location)
  center.value = newVal.location
  local_position.lat = newVal.location.lat
  local_position.lng = newVal.location.lng
  markerRef.value.marker.setGeometries([
    {
      styleId: 'marker',
      position: local_position,
      properties: {
        title: newVal.title
      }
    }
  ])
  emit('locationSelected', newVal.location)
})

// 获取IP和城市信息（示例）
const fetchIpAndCity = async (query) => {
  const res = await suggestionInfo({ region: '吉林', keyword: query })
  if (res.status === 0) {
    console.log('res===', res)
    optionsList.value = res.data.map((item) => ({
      value: item,
      label: `${item.title}`
    }))
  }
  loading.value = false
}
const optionsList = ref([])
const loading = ref(false)
const states = []

// 生命周期钩子替代 mounted
onMounted(() => {
  optionsList.value = states.map((item) => ({
    value: `value:${item}`,
    label: `label:${item}`
  }))
  // 直接赋值给 options 或其他操作
})

// 定义 remoteMethod 方法
const remoteMethod = (query) => {
  console.log('query=', query)
  console.log('value=', valueSearch.value)
  if (query !== '') {
    loading.value = true
    fetchIpAndCity(query)
  } else {
    optionsList.value = []
  }
}

const onMapInited = () => {
  // 地图加载完成后，可以获取地图实例、点标记实例，调用地图实例、点标记实例方法
  // console.log(mapRef.value.map)
  local_position = markerRef.value.marker.geometries[0].position
  console.log('markerRef.value.marker', local_position)
  emit('locationSelected', local_position)
}

const getLayerInstance = () => {
  // 可以获取点标记实例，调用点标记实例方法

  console.log('makerRef', markerRef.value)
}

const control = {
  scale: {},
  zoom: {
    position: 'topRight'
  }
}

const geometries = ref([
  {
    styleId: 'marker',
    position: props.Location,
    properties: {
      title: '这是自定义数据'
    }
  }
])

const styles = {
  marker: {
    width: 30, // 样式宽
    height: 45, // 样式高
    anchor: { x: 10, y: 30 } // 描点位置
    // enableRelativeScale: true, // 是否开启相对缩放
  }
}

const options = {
  minZoom: 5,
  maxZoom: 20
}
</script>

<style>
.map-search-container {
  margin: 10px 0px;
}
</style>
